package com.tobeface.wechat.request;

import com.tobeface.modules.lang.Langs;

import java.net.URLEncoder;
import java.util.Map;

/**
 * @author loudyn
 */
final class WeChatRequestURLBuilder {

    /**
     * @param request
     * @return
     */
    static String buildQueryUrl(WeChatRequest request) {

        String url = request.getUrl();

        // clean frament.
        if (url.indexOf("#") > 0) {
            url = url.substring(0, url.indexOf("#"));
        }

        int qp = url.indexOf("?");
        if (qp == -1) {
            url = url + "?";
        } else if (qp < url.length() - 1 && !url.endsWith("&")) {// has params and not endwith '&'
            url = url + "&";
        }

        StringBuilder buf = new StringBuilder().append(url);
        Map<String, String> queryParams = request.getQueryParams();
        for (Map.Entry<String, String> entry : queryParams.entrySet()) {
            buf.append(urlEncode(entry.getKey())).append("=");
            buf.append(urlEncode(entry.getValue())).append("&");
        }
        return buf.toString();
    }

    private static String urlEncode(String param) {
        try {

            return URLEncoder.encode(param, "UTF-8");
        } catch (Exception e) {
            throw Langs.toUncheck(e);
        }
    }
}
